<template>
	<view class="uiwu uiwu-ios" :style="{'padding-top': statusBar +'px'}">
		<view class="uiwu-box">
			<!-- 头部信息 -->
			<uiwu-goods-header :dataInfo="dataInfo" @changTips="swiperAudio" />
			<view class="uiwu-video">

				<view class="uiwu-video-box" style="position: relative;">
					<view class="loading" v-if="loading">
						<image src="/static/loading.png" mode=""></image>
						<text>{{uiwu.lang('加载中...')}}</text>
					</view>
					<div ref="videoBox" id="videoBox">

					</div>
					<view @animationend="animationend" v-if="prizeState != 0"
						:class="prizeState == 2?'hidePrize':' animate__animated animate__shakeY animate__slow'"
						class="prizeBox">
						<image :src="dataInfo.product_info?.image" mode="aspectFill"></image>
					</view>
					<view v-if="showHave && isExecute && duration > 0" class="daojishi">{{duration}}s</view>
				</view>
				<view class="uiwu-video-top uiwu-flex-space">
					<view v-if="!thatUser"></view>
					<view v-else class="left">
						<image v-show="thatUser.is_vip" src="/static/huanguan.png" mode="widthFix"></image>
						<image :src="thatUser.avatar" mode="aspectFill" style="border-radius: 50%"></image>
						<image src="/static/green.png" mode="widthFix"></image>
					</view>
					<view class="right uiwu-flex-space">
						<view class="image" v-if="roomlist.length > 3">
							<image v-for="(item,index) in 3" :key="index" :src="roomlist[index].avatar"
								mode="aspectFill"></image>
						</view>
						<view class="image" v-else>
							<image v-for="(item,index) in roomlist" :key="index" :src="item.avatar" mode="aspectFill">
							</image>
						</view>
						<view class="text">
							{{roomlist.length}}人 <br> {{uiwu.lang('在房间')}}
						</view>
					</view>
				</view>
				<!-- 控制音频 -->
				<!-- <view class="uiwu-audio">
						<image src="/static/audio.png" v-if="isAudio" mode="widthFix" @tap.stop="swiperAudio"></image>
						<image src="/static/stopaidop.png" v-else mode="widthFix" @tap.stop="swiperAudio"></image>
					</view> -->
				<!-- 广播抓中的人 -->
				<view class="uiwu-guangbo uiwu-flex-align" v-if="resultAllData">
					<image :src="resultAllData.avatar" mode="aspectFill"></image>
					<text class="uiwu-hidden1">{{resultAllData.nickname}}抓中了{{resultAllData.product_name}}</text>
				</view>
				<!-- <view class="swiper-root uiwu-flex-column uiwu-flex-center" @tap.stop="swiperDevice">
						<image src="/static/qiehuanroot.png" mode="widthFix"></image>
						<text>切换房间</text>
					</view> -->
				<view class="advertisement" v-if="tmp == 'toutiao'">
					<image @tap.stop="completeFun" src="/static/guanggao.png" mode="widthFix"></image>
				</view>
			</view>
			<!-- 开始按钮 -->
			<uiwu-goods-start 
				ref="isReservation" 
				v-if="!showHave"
				:dataInfo="dataInfo"
				:is_blocked="is_blocked"
				@moneyBuZu="showMoney=true" 
				@onStart="onStartFun"
				@toShowDetail="showDetail = true" 
				@changeUpdate="getDeviceinfo" 
				@videoInit="videoInitFun" 
			/>
			<!-- 游戏进行中 -->
			<uiwu-goods-have
				v-else
				:isExecute="isExecute" 
				:item="dataInfo"  
				@onStart="gardStart"
				@deactive="gardDeactive" 
				@direction="gardDirection" 
			/>
		</view>
		<template v-if="showDetail">
			<view class="uiwu-goods-yeool">
				<view class="uiwu-goods-detail">
					<view class="title">
						<view class="tabs">
							<view class="tab" :class="tabIndex == 0 ? 'active' : ''" @tap="tabChange(0)">{{uiwu.lang('商品详情')}}</view>
							<view class="tab" :class="tabIndex == 1 ? 'active' : ''" @tap="tabChange(1)">{{uiwu.lang('用户须知')}}</view>
							<view class="tab" :class="tabIndex == 2 ? 'active' : ''" @tap="tabChange(2)">{{uiwu.lang('抓中记录')}}</view>
						</view>
						<image @click="showDetail = false" src="../../static/close.png" mode=""></image>
					</view>
					<scroll-view scroll-y="true" style="padding: 20rpx;height: 760rpx;width:710rpx" @scrolltolower="bottomFun">
						<mp-html :content="description" v-if="tabIndex == 0"></mp-html>

						<view class="xuzhi" v-if="tabIndex == 1">
							<view class="title">{{titleText}}</view>
							<view class="tips" v-html="textWord"></view>
						</view>

						<view class="zz-list" v-if="tabIndex == 2">
							<view class="item" v-for="(item,index) in zz_list" :key="index">
								<view class="user">
									<image :src="item.avatar" mode="aspectFill" class="avatar"></image>
									<view class="nickname">{{ item.nickname }}</view>
								</view>

								<view class="time">{{ item.time_tran }}</view>
							</view>
						</view>
					</scroll-view>
				</view>
			</view>
			<view class="mark" @click="showDetail = false"></view>
		</template>
		<uiwu-goods-NoPopup :dataInfo="dataInfo" v-if="noGoodsPopup" @continue="continueGame" @closegrme="closegrme" />
		<uiwu-goods-yePopup :dataInfo="dataInfo" :goodsName="goodsName" v-if="yesGoodsPopup" @continue="continueGame" @closegrme="closegrme" />
		<uiwu-start-popup :dataInfo="dataInfo" @onStart="onStartCange" v-if="isYuyueStart" @closegrme="closegrme" />
		<uiwu-popup-model v-if="showMoney" v-model="showMoney" @confirm="confirm">
			<template v-slot:content>
				<text>{{uiwu.lang('哎呀，金币不够了')}}</text>
			</template>
		</uiwu-popup-model>
	</view>
</template>

<script setup lang="ts">
	import { onLoad, onUnload, onReady } from '@dcloudio/uni-app';
	import { inject, ref } from "vue";
	import { deviceinfo, startGren, cancel_subscribe, deviceRandInfo, sysConfig, apiGetList , agreement } from "@/api/api";
	import { uiwu } from '@/config/config';
	import { socket } from '@/config/ws';
	const showHave = ref<boolean>(false)
	const dataInfo = ref<any>({});
	const devId = ref(null)
	const noGoodsPopup = ref(false)
	const yesGoodsPopup = ref(false)
	const goodsName = ref(null)
	const isYuyueStart = ref(false)
	const isReservation = ref(null)
	const roomlist = ref([])
	const store = inject<any>('store');
	const isExecute = ref<boolean>(true) //下抓锁定条件
	const roomId = ref(null)
	const thatUser = ref(null)
	const showMoney = ref(false)
	const AudioContext = uni.createInnerAudioContext() // 游戏背景音乐
	const AudioContext2 = uni.createInnerAudioContext() // 操作音乐
	const AudioContext3 = uni.createInnerAudioContext() // 下抓音乐
	const duration = ref(0)
	let t_duration = null;
	const description = ref(null)
	const isAudio = ref(true)
	const resultAllData = ref(null)
	const showDetail = ref(false)
	let setTimeOutRestle = null
	const prizeState = ref(0)
	const loading = ref(true)

	const videoBox = ref(null)
	const tabIndex = ref(0)
	const textWord = ref('')
	const titleText = ref('')

	const page_no = ref(1)
	const zz_list = ref([])
	const is_blocked = ref(false) // 是否被浏览器事件阻止
	let player:any = {}, oldurl = ''
	onReady(() => {
		const video = document.createElement('video');
		video.setAttribute('id', 'myvideo');
		video.setAttribute('ref', 'myvideo');
		video.setAttribute('playsinline', true);
		video.setAttribute('webkit-playsinline', true);
		const rate = 270 / 477
		const width = videoBox.value.clientWidth
		const height = Math.round(videoBox.value.clientWidth / rate)
		video.setAttribute('style', `width: ${width}px; height: ${height}px`);
		videoBox.value.appendChild(video)

		player = TCPlayer('myvideo', {
			licenseUrl: 'https://license.vod2.myqcloud.com/license/v2/1300121492_1/v_cube.license',
			autoplay: true,
			bigPlayButton: false,
			muted: true,
			controls: false
		});
		player.on('play', () => {
			loading.value = false
			videoBox.value.style.opacity = 1
			prizeState.value = 1
		})

		player.on('error', () => { })

		player.on('blocked', () => {
			is_blocked.value = true;
		})
	})
	const initVideo = (url:string) => {
		if (oldurl != url) {
			player.src(url);
			oldurl = url
		}
	}

	const animationend = () => {
		prizeState.value = 2
	}

	const tabChange = (index:any) => {
		tabIndex.value = index;

		if (index == 1) {
			getAgreement();
		}

		if (index == 2) {
			getList();
		}
	}

	const bottomFun = () => {
		if (tabIndex.value == 2) {
			getList()
		}
	}

	const getAgreement = async () : Promise<any> => {
		const { data } = await agreement(3);
		data.content = uiwu.richtext(data.content)
		textWord.value = data.content
		titleText.value = data.title
	}

	const getList = async () => {
		const { data, status } = await apiGetList({
			page: page_no.value,
			limit: 10,
			device_id: dataInfo.value.device_info.id
		})

		if (page_no.value > data.last_page) return;

		if (status == 200) {
			zz_list.value.push(...data.data);
			page_no.value++;
		}
	}

	const getDeviceinfo = async (id : string = devId.value) : Promise<any> => {
		const { data } = await deviceinfo(id);
		if (data.monitor_list[0]) {
			initVideo(data.monitor_list[0].monitor_url)
		}

		data.product_info.description = uiwu.richtext(data.product_info.description)
		description.value = data.product_info.description
		dataInfo.value = data
		const { device_info } = data;
		duration.value = device_info.duration

		let leftTime = Math.round(data.device_info.duration - (data.current_time - data.device_info.game_start_time))
		if (data.is_current_gamer == 1 && data.device_info.state == 1 && leftTime > 0) {
			checkState(leftTime)
			prizeState = 0
		}
	}

	const checkState = (leftTime:any) => {
		showHave.value = true;
		duration.value = leftTime
		t_duration = setInterval(() => {
			duration.value--
			if (duration.value == 0) {
				clearInterval(t_duration)
			}
		}, 1000)
	}

	const confirm = () => {
		uniWeb.switchTab({
			url: '/pages/recharge/recharge'
		})
	}
	const swiperAudio = () : void => {
		isAudio.value = !isAudio.value
		if (!isAudio.value) AudioContext.pause()
		if (isAudio.value) AudioContext.play()
	}
	/**
	 * getSysConfig 获取音频地址
	 */
	const getSysConfig = async () => {
		const { data } = await sysConfig();
		let url = data.data
		isAudio.value = data.is_open_music == 1 ? true : false
		AudioContext2.src = data.operate_sound;
		AudioContext3.src = data.grab_sound;
		if (url && isAudio.value) {
			AudioContext.src = url
			AudioContext.loop = true
			AudioContext.play()
		}
	}
	const gardStart = () => {
		isExecute.value = false
		clearInterval(t_duration)

		uni.showLoading({
			title: uiwu.lang('等待抓取结果...'),
			mask: true
		})

		if (isAudio.value) {
			AudioContext.pause();
			AudioContext2.pause();
			AudioContext3.play();

			setTimeout(() => {
				AudioContext.play();
				AudioContext3.stop();
				uni.hideLoading();
			}, 4000)
		} else {
			setTimeout(() => {
				uni.hideLoading();
			}, 4000)
		}
	}

	// 移动结束监听
	const gardDeactive = () => { }

	// 移动事件监听
	const gardDirection = () => {
		if (isAudio.value) {
			AudioContext2.play();
			AudioContext3.stop();
		}
	}

	/**
	 * 开始游戏的回调 回调房间id 用于继续游戏
	 */
	const onStartFun = (id:any) => {
		roomId.value = id
	}

	// 如果被浏览器拦截 需要手动调取画面
	const videoInitFun = () => {
		player.play();
		AudioContext.play()
		is_blocked.value = false;
	}

	uni.$on('receivedMsgCallBack', (res) => {
		try {
			const { data, type, user_info, status } = JSON.parse(res);
			// 获取抓取结果
			if (type == 'grabResult') {
				if (data.status == 0) noGoodsPopup.value = true
				if (data.status == 1) {
					goodsName.value = data.product_name
					yesGoodsPopup.value = true
				}
				showHave.value = false
			}
			if (type == 'subscribeStart') isYuyueStart.value = true // 预约到自己上场弹窗
			if (type == 'groupUserList') roomlist.value = data //当前房间人数
			if (type == 'currentPlayer') thatUser.value = user_info //当前玩家信息
			if (type == 'deviceStatus') dataInfo.value.device_info.state = status //设备状态
			if (type == 'subscribeNum') dataInfo.value.subscribe_num = data.subscribe_num //预约人数
			// 广播推送 抓中奖品的人
			if (type == 'grabResultAll') {
				resultAllData.value = data
				clearTimeout(setTimeOutRestle) //先清除定时器
				// 5秒后关闭广播弹窗
				setTimeOutRestle = setTimeout(() => {
					resultAllData.value = null
				}, 5000)
			}
			//投币结果
			if (type == 'insertCoinResult') {
				if (status != 1) return uiwu.toast(uiwu.lang('投币失败，请重试'))
				showHave.value = true
				clearInterval(t_duration)
				t_duration = setInterval(() => {
					duration.value--
					if (duration.value == 0) {
						AudioContext.pause();
						AudioContext2.pause();
						AudioContext3.play();

						uni.showLoading({
							title: uiwu.lang('等待抓取结果...'),
							mask: true
						})

						setTimeout(() => {
							AudioContext.play();
							AudioContext3.stop();
							uni.hideLoading();
						}, 4000)
						clearInterval(t_duration)
					}
				}, 1000)
			}
		} catch (e) {
			console.log(e);
		}
	})
	const onStartCange = () => {
		showHave.value = true;
		isYuyueStart.value = false
	}
	/**
	 * 没有抓中奖品后，弹窗继续游戏
	 */
	const continueGame = async () : Promise<any> => {
		const { device_info } = dataInfo.value;
		const result = await startGren({
			device_id: device_info.id,
			room_id: roomId.value
		})
		noGoodsPopup.value = false
		isExecute.value = true
		if (!result) return
		if (result.data.room_id == 'now_money_lack' || result.data.id == 'now_money_lack') {
			closegrme()
			showMoney.value = true
			return
		}
		duration.value = dataInfo.value.device_info.duration
		clearInterval(t_duration)
		t_duration = setInterval(() => {
			duration.value--
			if (duration.value == 0) {
				clearInterval(t_duration)
			}
		}, 1000)
		if (result.data.id) roomId.value = result.data.id
	}
	/**
	 * closegrme 没有抓中奖品后 默认倒计时结束，游戏结束
	 */
	const closegrme = () => {
		roomId.value = null
		isExecute.value = true
		showHave.value = false
		noGoodsPopup.value = false
		thatUser.value = null
		duration.value = dataInfo.value.device_info.duration
		yesGoodsPopup.value = false
		if (isYuyueStart.value) {
			isYuyueStart.value = false
			isReservation.value.setisReservation()
			getDeviceinfo()
		}
		getDeviceinfo()
	}
	/**
	 * swiperDevice 切换房间 
	 * 这里利用的是页面关闭重新打开的操作模式实现数据重载。
	 * 因为牵扯到了renderjs 不知道怎么重新触发故而只能使用次下策方式
	 */
	const swiperDevice = async () : Promise<any> => {
		uni.showLoading({
			title: uiwu.lang('切换中')
		})
		const { device_info } = dataInfo.value;
		const { data: { id } } = await deviceRandInfo(device_info.id);
		initPage(id)
		uni.hideLoading()
	}
	const completeFun = () => {
		uniWeb.navigateTo({
			url: '/pages/index/ad?id=' + devId.value
		})

	}
	onUnload(() => {
		AudioContext.destroy()
		uni.$off('receivedMsgCallBack')
		uni.$off('onRegister')
		if (isReservation.value?.getisReservation()) {
			cancel_subscribe({ device_id: dataInfo.value.device_info.id })
		}
		socket.send(JSON.stringify({
			type: 'leaveGroup',
			device_id: dataInfo.value.device_info.id
		}));
	})
	const initPage = (id:any) => {
		devId.value = id
		getDeviceinfo();
		getSysConfig()

	}
	let tmp = ref('app')
	const statusBar = ref(0)
	onLoad((op) => {
		tmp.value = op.tmp
		statusBar.value = op.statusBar || 0
		initPage(op.id)
		uni.$on('onRegister', () => {
			socket.send(JSON.stringify({
				type: 'joinGroup',
				device_id: op.id
			}));
		})

	})
</script>
<style lang="scss" scoped>
	page {
		background: url('../../static/yuandian.png') no-repeat 0 0;
		background-size: 100% 100%;
	}

	.uiwu {
		padding-left: 5rpx;
		padding-right: 5rpx;
		padding-bottom: 5rpx;
	}

	.uiwu-box {
		width: 100%;
		height: 1466rpx;
		background: url('../../static/detaigb.png') no-repeat 0 0;
		background-size: 100% 100%;
		position: relative;
		z-index: 9;
	}

	.uiwu-video {
		width: 100%;
		height: 950rpx;
		// background: url('../../static/videoborder.png') no-repeat 0 84rpx;
		// background-size: 100% 800rpx;
		position: relative;
		margin-bottom: 130rpx;

		.uiwu-audio {
			position: absolute;
			right: 40rpx;
			top: 104rpx;

			image {
				width: 56rpx;
			}
		}

		.uiwu-guangbo {
			position: absolute;
			left: 40rpx;
			top: 200rpx;
			max-width: 360rpx;
			height: 60rpx;
			background: rgba(0, 0, 0, 0.4);
			border-radius: 30rpx;
			border: 1rpx solid #000000;
			padding: 2rpx;
			padding-right: 15rpx;

			image {
				width: 54rpx;
				height: 54rpx;
				border-radius: 50%;
				margin-right: 15rpx;
			}

			text {
				font-size: 24rpx;
				font-weight: 500;
				color: #FFFFFF;
			}
		}

		.uiwu-video-box {
			width: 100%;
			height: 100%;
			padding: 4px 20rpx;
			overflow: hidden;
			position: relative;

			.prizeBox {
				width: 350rpx;
				height: 350rpx;
				border-radius: 20rpx;
				position: absolute;
				top: 300rpx;
				left: 200rpx;
				overflow: hidden;


				image {
					width: 100%;
					height: 100%;
				}
			}

			.prizeBox.hidePrize {
				transition: all ease-in-out 1.5s;
				top: 1100rpx !important;
				left: 100rpx !important;
				width: 0;
				height: 0;
				opacity: 0;
			}

			.loading {
				position: absolute;
				width: 194rpx;
				top: 50%;
				left: 50%;
				transform: translate(-50%, -70%);
				display: flex;
				flex-direction: column;
				align-items: center;
				color: #913500;
				font-size: 32rpx;
				font-weight: bold;

				image {
					width: 194rpx;
					height: 246rpx;
					margin-bottom: 10rpx;
				}
			}

			#videoBox {
				width: 100%;
				height: 100%;
				background-color: #000;
				overflow: hidden;
				border-radius: 20rpx;
				opacity: 0;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.daojishi {
				position: absolute;
				left: 40rpx;
				bottom: 40rpx;
				font-size: 60rpx;
				color: #FFF;
			}
		}

		.left {
			position: relative;

			image {
				&:nth-child(1) {
					width: 36rpx;
					position: absolute;
					left: 6rpx;
					top: 6rpx;
				}

				&:nth-child(2) {
					width: 80rpx;
					height: 80rpx;
				}

				&:nth-child(3) {
					position: absolute;
					right: 6rpx;
					bottom: 6rpx;
					width: 20rpx;
				}
			}
		}

		.swiper-root {
			position: absolute;
			right: 0;
			bottom: 355rpx;
			width: 100rpx;
			height: 104rpx;
			background: linear-gradient(180deg, #FCE5C7 0%, #FAC500 100%);
			border-radius: 20rpx;
			border: 3rpx solid #231815;

			image {
				width: 56rpx;
			}

			text {
				font-size: 20rpx;
				font-weight: bold;
				color: #913500;
			}
		}

		.advertisement {
			position: absolute;
			right: 20rpx;
			bottom: 50rpx;

			image {
				width: 180rpx;
			}
		}

		&-top {
			width: 100%;
			height: 84rpx;
			position: absolute;
			left: 0;
			right: 0;
			top: 0;
			padding: 0 37rpx;

			.right {
				width: 214rpx;
				height: 60rpx;
				background: rgba(0, 0, 0, 0.4);
				border-radius: 30rpx;
				border: 3rpx solid #000000;
				box-sizing: content-box;

				.image {
					height: 56rpx;

					image {
						width: 56rpx;
						height: 56rpx;
						border-radius: 50%;

						&:nth-child(2) {
							margin-left: -32rpx;
						}

						&:nth-child(3) {
							margin-left: -32rpx;
						}
					}
				}

				.text {
					text-align: center;
					font-size: 22rpx;
					font-weight: 500;
					color: #FFFFFF;
					padding-right: 16rpx;
					line-height: 1.2;
				}
			}
		}

		.button {
			width: 600rpx;
			height: 60rpx;
			line-height: 60rpx;
			background: url('../../static/qiehuanshijiao.png') no-repeat 0 3rpx;
			background-size: 100% 100%;
			position: absolute;
			left: 0;
			right: 0;
			bottom: 0;
			margin: 0 auto;
			text-align: center;
			font-size: 28rpx;
			font-weight: 800;
			color: #231815;
		}
	}

	.uiwu-goods-yeool {
		border-radius: 32rpx;
		position: fixed;
		bottom: 0;
		left: 0;
		height: 900rpx;
		border-radius: 30rpx 30rpx 0 0;
		background-color: #fff;
		z-index: 9999;
	}

	.mark {
		position: fixed;
		z-index: 9998;
		background-color: rgba(0, 0, 0, 0.5);
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
	}

	.uiwu-goods-detail {
		// background: url('../../static/goodsdetail.png') no-repeat center -4rpx #FFF;
		background-color: #FFF;
		background-size: 600rpx 60rpx;
		min-height: 400rpx;
		border: 3rpx solid #231815;
		border-radius: 32rpx;

		.zz-list {
			margin-bottom: 40rpx;

			.item {
				display: flex;
				align-items: center;
				margin-bottom: 24rpx;

				&:last-child {
					margin-bottom: 0;
				}

				.user {
					display: flex;
					align-items: center;
					flex: 1;

					.avatar {
						width: 80rpx;
						height: 80rpx;
						border-radius: 10rpx;
					}

					.nickname {
						font-size: 30rpx;
						color: #999;
						margin-left: 24rpx;
					}
				}

				.time {
					font-size: 30rpx;
					color: #999;
				}
			}
		}

		.xuzhi {
			.title {
				font-size: 32rpx;
				font-weight: bold;
				color: #231815;
				margin-bottom: 20rpx;
			}

			.tips {
				font-size: 28rpx;
				font-weight: 500;
				color: #444444;
				min-height: 300rpx;
			}
		}

		.title {
			font-size: 28rpx;
			font-weight: 800;
			line-height: 54rpx;
			position: relative;

			image {
				position: absolute;
				right: 24rpx;
				top: 12px;
				width: 40rpx;
				height: 40rpx;
			}


			.tabs {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 20rpx 40rpx;
				margin-right: 80rpx;

				.tab {
					color: #999;
				}

				.active {
					color: #000;

					position: relative;

					&::after {
						content: '';
						border-radius: 10rpx;
						height: 10rpx;
						position: absolute;
						left: 0;
						right: 0;
						bottom: 0;
						background-color: #F6AA00;
					}
				}
			}
		}
	}
</style>